<template>
  <el-table ref="treeTable"  :data="formatData" :row-style="showRow" v-bind="$attrs">
    <slot/>
  </el-table>
</template>

<script>
export default {
  name: 'TreeTable',
  props: {
    data: {
      type: [Array, Object],
      required: true
    },
    expandAll: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    formatData () {
      return this.evalTree(this.data, this.expandAll);
    }
  },
  provide () {
    return {
      toggleExpanded: this.toggleExpanded
    }
  },
  methods: {
    iconShow (record) {
      return (record.children && record.children.length > 0);
    },
    showRow (row) {
      const show = (row.row.parent ? (row.row.parent._expanded && row.row.parent._show) : true)
      row.row._show = show
      return show ? 'animation:treeTableShow 1s;-webkit-animation:treeTableShow 1s;' : 'display:none;'
    },
    // 切换下级是否展开
    toggleExpanded (index) {
      const record = this.formatData[index];
      record._expanded = !record._expanded
      // 表格数据发生变化，将会重新渲染表格
    },
    /**
     * 解析树相关的数据
     * 添加expand parent level属性
     */
    evalTree (data, expandAll = false, parent = null, level = null) {
      let tmp = [];
      var that = this;
      Array.from(data).forEach(function (record) {
        if (record._expanded === undefined) {
          that.$set(record, '_expanded', expandAll);
        }
        let _level = 1;
        if (level !== undefined && level !== null) {
          _level = level + 1;
        }
        that.$set(record, '_level', _level);
        if (parent) {
          that.$set(record, 'parent', parent);
        }
        tmp.push(record);
        if (record.children && record.children.length > 0) {
          const children = that.evalTree(record.children, expandAll, record, _level);
          tmp = tmp.concat(children);
        }
      });
      return tmp;
    }
  }
}
</script>
